﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MultiDAQ_Analysis.License;
using LicenseManager = MultiDAQ_Analysis.License.LicenseManager;
namespace MultiDAQ_Analysis.View
{
    public partial class LicenseInputForm : Form
    {
        public string LicenseText { get; private set; }

        private TextBox txtLicense;
        private Button btnOK;
        private Button btnCancel;
        private Label lblDeviceUID;
        private Label lblInstruction;
        private GroupBox groupBox1;
        private Label lblTitle;
        private Button btnCopyUID;
        private TextBox txtDeviceUID; // 改为TextBox便于复制

        public LicenseInputForm()
        {
            InitializeComponent();
        }

        private void InitializeComponent()
        {
            this.SuspendLayout();

            // Form 设置
            this.ClientSize = new Size(600, 480);
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.StartPosition = FormStartPosition.CenterParent;
            this.Text = "软件激活";
            this.ShowIcon = false;
            this.BackColor = SystemColors.Control;

            // 标题
            lblTitle = new Label()
            {
                Text = "软件许可证激活",
                Location = new Point(20, 20),
                Size = new Size(560, 25),
                Font = new Font("Microsoft YaHei", 12F, FontStyle.Bold),
                ForeColor = Color.FromArgb(64, 64, 64)
            };

            // 说明标签
            lblInstruction = new Label()
            {
                Text = "请将下方的设备标识码发送给软件供应商以获取许可证，然后在下面输入许可证字符串：",
                Location = new Point(20, 55),
                Size = new Size(560, 40),
                Font = new Font("Microsoft YaHei", 9F)
            };

            // 设备UID标签
            lblDeviceUID = new Label()
            {
                Text = "设备标识码:",
                Location = new Point(20, 105),
                Size = new Size(100, 20),
                Font = new Font("Microsoft YaHei", 9F)
            };

            // 设备UID文本框（便于复制）
            txtDeviceUID = new TextBox()
            {
                Location = new Point(120, 103),
                Size = new Size(350, 23),
                Font = new Font("Consolas", 9F),
                ReadOnly = true,
                BackColor = SystemColors.Control,
                BorderStyle = BorderStyle.FixedSingle
            };

            // 复制UID按钮
            btnCopyUID = new Button()
            {
                Text = "复制设备码",
                Location = new Point(480, 102),
                Size = new Size(100, 25),
                Font = new Font("Microsoft YaHei", 8F),
                UseVisualStyleBackColor = true
            };
            btnCopyUID.Click += BtnCopyUID_Click;

            // 分组框
            groupBox1 = new GroupBox()
            {
                Text = "许可证字符串",
                Location = new Point(20, 140),
                Size = new Size(560, 200),
                Font = new Font("Microsoft YaHei", 9F)
            };

            // 许可证输入框
            txtLicense = new TextBox()
            {
                Location = new Point(15, 25),
                Size = new Size(530, 160),
                Multiline = true,
                ScrollBars = ScrollBars.Both,
                Font = new Font("Consolas", 9F),
                WordWrap = false,
                BackColor = Color.White,
                BorderStyle = BorderStyle.FixedSingle,
                //PlaceholderText = "请在此处粘贴从软件供应商处获得的许可证字符串..."
            };

            // 添加提示文本
            var lblHint = new Label()
            {
                Text = "提示: 许可证是一段很长的字符串，请完整复制粘贴，不要遗漏任何字符。",
                Location = new Point(20, 350),
                Size = new Size(560, 20),
                Font = new Font("Microsoft YaHei", 8F),
                ForeColor = Color.Gray
            };

            // 确定按钮
            btnOK = new Button()
            {
                Text = "激活",
                Location = new Point(420, 410),
                Size = new Size(80, 35),
                Font = new Font("Microsoft YaHei", 9F),
                UseVisualStyleBackColor = true,
                FlatStyle = FlatStyle.System
            };
            btnOK.Click += BtnOK_Click;

            // 取消按钮
            btnCancel = new Button()
            {
                Text = "取消",
                Location = new Point(510, 410),
                Size = new Size(80, 35),
                Font = new Font("Microsoft YaHei", 9F),
                UseVisualStyleBackColor = true,
                DialogResult = DialogResult.Cancel,
                FlatStyle = FlatStyle.System
            };
            btnCancel.Click += BtnCancel_Click;

            // 添加控件到窗体
            groupBox1.Controls.Add(txtLicense);
            this.Controls.Add(lblTitle);
            this.Controls.Add(lblInstruction);
            this.Controls.Add(lblDeviceUID);
            this.Controls.Add(txtDeviceUID);
            this.Controls.Add(btnCopyUID);
            this.Controls.Add(groupBox1);
            this.Controls.Add(lblHint);
            this.Controls.Add(btnOK);
            this.Controls.Add(btnCancel);

            // 设置默认按钮和取消按钮
            this.AcceptButton = btnOK;
            this.CancelButton = btnCancel;

            // 设置Tab顺序
            txtLicense.TabIndex = 0;
            btnOK.TabIndex = 1;
            btnCancel.TabIndex = 2;
            btnCopyUID.TabIndex = 3;

            this.ResumeLayout(false);
        }

        /// <summary>
        /// 获取设备UID（带详细错误处理）
        /// </summary>
        private string GetDeviceUID()
        {
            try
            {
                // 检查LicenseManager是否已初始化
                if (!LicenseManager.IsInitialized())
                {
                    // 尝试基本的设备标识生成
                    string basicUID = GenerateBasicDeviceUID();
                    Console.WriteLine($"LicenseManager未初始化，使用基本方法生成UID: {basicUID}");
                    return basicUID;
                }

                string uid = LicenseManager.GetDeviceUID();

                // 验证UID是否有效
                if (string.IsNullOrEmpty(uid) || uid.Contains("ERROR") || uid.Contains("失败"))
                {
                    string basicUID = GenerateBasicDeviceUID();
                    Console.WriteLine($"LicenseManager返回的UID无效({uid})，使用基本方法: {basicUID}");
                    return basicUID;
                }

                Console.WriteLine($"成功获取设备UID: {uid}");
                return uid;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取设备UID时发生异常: {ex.Message}");
                string basicUID = GenerateBasicDeviceUID();
                Console.WriteLine($"异常恢复，使用基本方法: {basicUID}");
                return basicUID;
            }
        }

        /// <summary>
        /// 基本的设备UID生成方法（备用）
        /// </summary>
        private string GenerateBasicDeviceUID()
        {
            try
            {
                string machineName = Environment.MachineName ?? "UNKNOWN";
                string userName = Environment.UserName ?? "USER";
                string osVersion = Environment.OSVersion.VersionString ?? "OS";

                string combined = $"{machineName}_{userName}_{osVersion}";

                // 使用简单的哈希生成固定长度的UID
                int hash = combined.GetHashCode();
                return $"BASIC_{Math.Abs(hash):X8}";
            }
            catch (Exception ex)
            {
                // 最后的备用方案
                Console.WriteLine($"基本UID生成也失败: {ex.Message}");
                return $"FALLBACK_{DateTime.Now.Ticks:X}";
            }
        }

        /// <summary>
        /// 复制设备UID按钮点击事件
        /// </summary>
        private void BtnCopyUID_Click(object sender, EventArgs e)
        {
            try
            {
                string deviceUID = txtDeviceUID.Text;

                if (string.IsNullOrEmpty(deviceUID))
                {
                    MessageBox.Show("设备标识码为空，无法复制。", "提示",
                        MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 清空剪贴板
                Clipboard.Clear();

                // 复制到剪贴板
                Clipboard.SetText(deviceUID);

                // 验证复制是否成功
                string clipboardText = Clipboard.GetText();
                if (clipboardText == deviceUID)
                {
                    MessageBox.Show($"设备标识码已成功复制到剪贴板！\n\n复制的内容: {deviceUID}", "复制成功",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("复制可能失败，请手动选择设备标识码进行复制。", "复制警告",
                        MessageBoxButtons.OK, MessageBoxIcon.Warning);

                    // 选中文本框中的所有文本
                    txtDeviceUID.SelectAll();
                    txtDeviceUID.Focus();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"复制设备标识码时发生错误: {ex.Message}\n\n请手动选择文本进行复制。", "复制失败",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);

                // 选中文本框中的所有文本，用户可以手动复制
                txtDeviceUID.SelectAll();
                txtDeviceUID.Focus();
            }
        }

        private void BtnOK_Click(object sender, EventArgs e)
        {
            const string placeholderText = "请在此处粘贴从软件供应商处获得的许可证字符串...";

            string license = txtLicense.Text.Trim();

            // 检查是否仍然是占位符文本
            if (string.IsNullOrEmpty(license) || license == placeholderText)
            {
                MessageBox.Show("请输入许可证字符串。", "提示",
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtLicense.Focus();

                // 清除占位符文本
                if (txtLicense.Text == placeholderText)
                {
                    txtLicense.Text = "";
                    txtLicense.ForeColor = SystemColors.WindowText;
                }
                return;
            }

            // 进行基本的格式验证
            if (!IsValidLicenseFormat(license))
            {
                var result = MessageBox.Show("许可证格式看起来不正确。\n\n是否仍要尝试激活？", "格式警告",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

                if (result != DialogResult.Yes)
                {
                    txtLicense.Focus();
                    return;
                }
            }

            LicenseText = license;
            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        private void BtnCancel_Click(object sender, EventArgs e)
        {
            // 确认用户真的要取消
            var result = MessageBox.Show("确定要取消激活吗？\n\n取消后程序将退出。", "确认取消",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);

            if (result == DialogResult.Yes)
            {
                this.DialogResult = DialogResult.Cancel;
                this.Close();
            }
            // 如果用户选择"否"，则什么都不做，继续停留在激活界面
        }

        private bool IsValidLicenseFormat(string license)
        {
            try
            {
                // 基本检查
                if (license.Length < 50)
                {
                    return false;
                }

                // 简单的Base64格式检查
                Convert.FromBase64String(license);
                return true;
            }
            catch
            {
                return false;
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            // 初始化设备UID显示
            InitializeDeviceUID();

            // 设置焦点到许可证输入框
            txtLicense.Focus();
        }

        /// <summary>
        /// 初始化设备UID显示
        /// </summary>
        private void InitializeDeviceUID()
        {
            try
            {
                string uid = GetDeviceUID();
                txtDeviceUID.Text = uid;

                // 验证获取是否成功
                if (uid.Contains("ERROR") || uid.Contains("FALLBACK") || uid.Contains("失败"))
                {
                    lblDeviceUID.ForeColor = Color.Red;
                    MessageBox.Show("警告: 设备标识码生成可能不稳定。\n\n建议联系技术支持获取帮助。", "设备标识警告",
                        MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            catch (Exception ex)
            {
                txtDeviceUID.Text = $"获取失败: {ex.Message}";
                lblDeviceUID.ForeColor = Color.Red;

                MessageBox.Show($"无法获取设备标识码: {ex.Message}\n\n请联系技术支持。", "严重错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 重写窗体关闭事件，确保正确的DialogResult
        /// </summary>
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            // 如果用户直接关闭窗口（点击X按钮）
            if (this.DialogResult == DialogResult.None)
            {
                var result = MessageBox.Show("确定要取消激活吗？\n\n取消后程序将退出。", "确认取消",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);

                if (result == DialogResult.No)
                {
                    e.Cancel = true; // 取消关闭
                    return;
                }
                else
                {
                    this.DialogResult = DialogResult.Cancel; // 设置为取消
                }
            }

            base.OnFormClosing(e);
        }
    }
}